package hn.security.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import hn.security.constant.SecurityConstant;
import hn.security.message.SecurityResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("authenticationFailureHandler")
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    private static Logger logger = LoggerFactory.getLogger(AuthenticationFailureHandlerImpl.class);


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.info("{}:{}", e.getClass().getName(), e.getMessage());

        SecurityResponse securityResponse = null;
        if (e instanceof InternalAuthenticationServiceException) {//用户不存在
            securityResponse = SecurityResponse.failure(SecurityConstant.USER_NOT_EXIST);
        } else if (e instanceof BadCredentialsException) {//密码错误
            securityResponse = SecurityResponse.failure(SecurityConstant.PASSWORD_ERROR);
        } else if (e instanceof CredentialsExpiredException) {//密码过期
            securityResponse = SecurityResponse.failure(SecurityConstant.PASSWORD_EXPIRED);
        } else if (e instanceof DisabledException) {//账号不可用
            securityResponse = SecurityResponse.failure(SecurityConstant.ACCOUNT_DISABLE);
        } else if (e instanceof AccountExpiredException) {//账号已过期
            securityResponse = SecurityResponse.failure(SecurityConstant.ACCOUNT_EXPIRED);
        } else if (e instanceof LockedException) {//账号已锁定
            securityResponse = SecurityResponse.failure(SecurityConstant.ACCOUNT_LOCKED);
        } else {//未知错误
            securityResponse = SecurityResponse.failure(SecurityConstant.FAILURE);
        }
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        ObjectMapper objectMapper = new ObjectMapper();
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(securityResponse));


    }

}
